package com.sys.servlet;

import com.sys.dao.sysDao;
import com.sys.data.code;
import com.sys.util.console;
import net.sf.json.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.sys.util.stringUtils.StringIsEmptyOrNull;

@WebServlet(name = "inWarehouseItemServlet", urlPatterns = "/sys/inWarehouseItem", description = "物品入库")
public class inWarehouseItemServlet extends sysServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    setHeadHtml(req, resp, "inWarehouseItemServlet");
    sysDao dao = new sysDao();
    PrintWriter out = resp.getWriter();
    JSONObject backJson = new JSONObject();

    String itemName = req.getParameter("itemName");
    String warehouseId = req.getParameter("warehouseId");
    String itemType = req.getParameter("itemType");
    String supplierId = req.getParameter("supplierId");
    String itemBrokerage = req.getParameter("itemBrokerage");
    String itemPayType = req.getParameter("itemPayType");

    if (StringIsEmptyOrNull(itemBrokerage) || StringIsEmptyOrNull(warehouseId) || StringIsEmptyOrNull(itemType) || StringIsEmptyOrNull(supplierId) || StringIsEmptyOrNull(itemPayType) || StringIsEmptyOrNull(itemName)) {
      backJson.put("code", code.ErrorParam.value());
      backJson.put("msg", code.ErrorParam.msg());
      out.print(backJson);
      return;
    }
    try {
      int itemCount = Integer.parseInt(req.getParameter("itemCount"));
      int itemPrice = Integer.parseInt(req.getParameter("itemPrice"));
      dao.inWarehouseItem(itemName, warehouseId, itemType, itemCount, itemPrice, supplierId, itemBrokerage, itemPayType, out::print);
    } catch (Exception e) {
      e.printStackTrace();
      console.log("物品数量或单价填写错误");
      backJson.put("code", code.ErrorParam.value());
      backJson.put("msg", code.ErrorParam.msg());
      out.print(backJson);
    }
  }
}
